import { Shape, ShapeConfig } from "/graphic";
import { ILinearGradient } from "/graphic/shape/rect";
import { Graphic } from "/graphic/type";
import { Grender } from "/grender";
import { mixins } from "/tool";
import { isObject } from "/tool/is";
export function change<T>(this: Graphic, props: T) {
	const { parent: layer } = this;
	const shape = layer.children.find(shapes => shapes === this);
	if (!shape) {
		throw new Error("传入的【graphic】不存在");
	}
	shape.props = { ...shape.props, ...props };
	layer.refresh();
}
export function setShapeStyle<S>(
	style: CanvasRenderingContext2D,
	ctx: CanvasRenderingContext2D
) {
	if (!style || !isObject(style)) {
		return;
	}
	Object.keys(style).forEach((key: keyof CanvasRenderingContext2D) => {
		// @ts-ignore
		ctx[key] = style[key as keyof CanvasRenderingContext2D];
	});
}
export function fillLinearGradient(
	this: Graphic,
	linearGradient: ILinearGradient
) {
	const { parent } = this;
	if (!parent) {
		this.renderQueue.addJob(() =>
			fillLinearGradient.call(this, linearGradient)
		);
		return;
	}
	const { start, end, colorStops } = linearGradient;
	const { ctx } = parent.painter;
	const gradient = ctx.createLinearGradient(start.x, start.y, end.x, end.y);
	colorStops.forEach(color => {
		gradient.addColorStop(color[0], color[1]);
	});
	this.props.style.fillStyle = gradient;
	parent.refresh();
}

export function drawImage(this: Graphic, img: HTMLImageElement,...option:number[]) {
	const { parent } = this;
	const [drawX,drawY,drawOffsetX,drawOffsetY]=option;
	if (!parent) {
		this.renderQueue.addJob(() => drawImage.call(this, img,drawX,drawY,drawOffsetX,drawOffsetY));
		return;
	}
	const { ctx } = this.parent.painter;
	const { shape } = this.props;
	img.onload = ()=> {
		// 在圆形内填充图片
		ctx.save();
		ctx.clip(); // 剪切路径为圆形区域
		Object.assign(this.config,{drawX,drawY,drawOffsetX,drawOffsetY,drawImg:img})
		// ctx.restore()
		// this.parent.refresh()
	};
}
export default (instance: object) => {
	mixins(instance, { change, setShapeStyle, fillLinearGradient, drawImage });
};
